package com.bee.gateway.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.bee.commons.cache.CacheService;
import com.bee.gateway.common.constants.GatewayRedisConst;
import com.bee.gateway.server.service.AuthService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 鉴权
 * @author Damin.yang
 * @date 2019/08/07 15:30
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Autowired
    private CacheService cacheService;

    private List<String> ignoreUrls = Lists.newArrayList();

    @Override
    public void loadIgnoreUrls() {
        List<String> ignoreList = Lists.newArrayList();
        Set<String> keys = cacheService.keys(GatewayRedisConst.GATEWAY_IGNORE_AUTH_PREFIX);
        log.info(">>> load ignore url redis key size {}, datas: {}", keys.size(), JSON.toJSONString(keys));
        if (CollectionUtils.isNotEmpty(keys)) {
            List<Object> list = cacheService.multiGet(keys);
            log.info("load keys datas: {}", JSON.toJSONString(list));
            list.forEach(o -> {
                ignoreList.add((String) o);
            });
        }
        ignoreUrls = ignoreList;
    }

    @Override
    public boolean isIgnore(String uri) {
        return ignoreUrls.stream().anyMatch(ignoreUrl -> uri.equals(ignoreUrl));
    }

    @Override
    public void addUri(String uri) {
        ignoreUrls.add(uri);
    }

    @Override
    public void updateUri(String oUri, String uri) {
        addUri(uri);
        deleteUri(oUri);
    }

    @Override
    public void deleteUri(String uri) {
        ignoreUrls.remove(uri);
    }


}
